import { defineStore } from "pinia";
import { ref } from "vue";
import { loginAPI } from "@/apis/user";
import { useCartStore } from "./cartStore"
import {mergeCartlistAPI} from '@/apis/cart'

export const useUserStore = defineStore('user', () => {
    const cartStore = useCartStore()
    // 定义管理用户数据的state
    const userInfo = ref({})   
    // 相应的action
    const getUserInfo = async({ account, password }) => {
        const res = await loginAPI({ account, password })
        userInfo.value = res.result  
        const data = cartStore.cartList.map(item => {
            return {
                skuId: item.skuId,
                selected: item.selected,
                count:item.count
            }
        })
        await mergeCartlistAPI(data)
        cartStore.updateNewList()
    }

    // 退出登录的action
    const clearUserInfo = () => {
        userInfo.value = {}
        cartStore.clearCart()
    }

    // 以对象格式return
    return {
        userInfo,
        getUserInfo,
        clearUserInfo
    }
},
    {
    persist:true,
})